package com.idcard.readcard;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.nfc.NfcAdapter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.core.widget.NestedScrollView;

import com.idcard.readcard.utils.DoubleClickUtil;
import com.idcard.readcard.utils.NfcUtils;
import com.idcard.readcard.utils.WaterMarkBg;
import  com.idcard.bean.IdCardData;
import  com.idcard.cache.SpUtlils;
import  com.idcard.enums.DecodeImageType;
import  com.idcard.enums.ReadCardType;
import  com.idcard.enums.StatusCode;
import com.idcard.listener.ReadCardListener;
import  com.idcard.utils.LogUtils;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;


public class MainActivitys extends Activity implements ReadCardListener {

    private boolean isInitOk = false;
    private boolean isStartRead = false;
    private TextView tv_state;
    private ImageView imgMan;
    private EditText et_address, et_baudrate, et_ip, et_port, et_appid;
    private TextView txtName, txtSex, txtNation, tvCopyright, txtPolice, txtCardID, txtDeviceDN, txtAddress, txtValid, txtY, txtM, txtD, txtDN, txtUid, txtElapsedTime;
    private Button bu_open, bu_close, bu_init, bu_destory, bu_save, bu_once_open;
    private CheckBox bu_openLog, bu_sound;
    private LinearLayout llSerialPort;
    private NestedScrollView base_scoll, logNestedScrollView;
    private RadioGroup imageTypeRadioGroup, readTypeRadioGroup;
    private int successTime;
    private int readTime;
    private long alltime;
    private long smallTime = 1500;
    private MediaPlayer player;
    //1.声明一个nfc的Adapter
    private NfcUtils nfcUtils;
    private static final int PERMISSIONS_REQUEST = 1;
    private static final String PERMISSION_WRITE_STORAGE = Manifest.permission.WRITE_EXTERNAL_STORAGE;
    private static final String PERMISSION_READ_STORAGE = Manifest.permission.READ_EXTERNAL_STORAGE;
    private static final String PERMISSION_INTERNET = Manifest.permission.INTERNET;
    private static final String PERMISSION_ACCESS_NETWORK_STATE = Manifest.permission.ACCESS_NETWORK_STATE;
    private String[] Permission = new String[]{PERMISSION_WRITE_STORAGE, PERMISSION_READ_STORAGE, PERMISSION_INTERNET, PERMISSION_ACCESS_NETWORK_STATE};

    // 读卡SDK
    private ReadSettingBuilder readSettingBuilder;
    private ReadCardOutMethod readCardManager;
    private int lastStatus = 1000;

    private final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            String deviceId = readCardManager.readCardDeviceid();
            txtDeviceDN.setText(deviceId);
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //nfc初始化设置
        nfcUtils = new NfcUtils(this);
        /* 申请程序所需权限 */
        if (!hasPermission()) {
            requestPermission();
        }
        initView();
        initBuilder();
        initlistener();
    }

    private void initView() {
        tv_state = findViewById(R.id.text);
        imgMan = findViewById(R.id.imgMan);
        txtName = findViewById(R.id.txtName);
        bu_once_open = findViewById(R.id.bu_once_open);
        txtSex = findViewById(R.id.txtSex);
        txtNation = findViewById(R.id.txtNation);
        txtPolice = findViewById(R.id.txtPolice);
        txtCardID = findViewById(R.id.txtCardID);
        txtAddress = findViewById(R.id.txtAddress);
        txtValid = findViewById(R.id.txtValid);
        txtY = findViewById(R.id.txtY);
        txtM = findViewById(R.id.txtM);
        txtD = findViewById(R.id.txtD);
        txtDN = findViewById(R.id.txtDN);
        txtUid = findViewById(R.id.txtUid);
        bu_open = findViewById(R.id.bu_open);
        bu_close = findViewById(R.id.bu_close);
        bu_openLog = findViewById(R.id.bu_openLog);
        txtDeviceDN = findViewById(R.id.txtDeviceDN);
        txtElapsedTime = findViewById(R.id.txtElapsedTime);
        bu_init = findViewById(R.id.bu_init);
        bu_destory = findViewById(R.id.bu_destory);
        tvCopyright = findViewById(R.id.tvCopyright);
        bu_save = findViewById(R.id.bu_save);
        et_address = findViewById(R.id.et_address);
        et_baudrate = findViewById(R.id.et_baudrate);
        et_appid = findViewById(R.id.et_appid);
        et_ip = findViewById(R.id.et_ip);
        et_port = findViewById(R.id.et_port);
        bu_sound = findViewById(R.id.bu_sound);
        base_scoll = findViewById(R.id.base_scoll);
        logNestedScrollView = findViewById(R.id.log_scroll);
        imageTypeRadioGroup = findViewById(R.id.rg_image_type);
        readTypeRadioGroup = findViewById(R.id.rg_read_type);
        llSerialPort = findViewById(R.id.ll_serialPort);
        bu_once_open.setVisibility(View.GONE);
        llSerialPort.setVisibility(View.GONE);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        try {
            String name = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
            tvCopyright.setText("版本号：" + name);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        player = MediaPlayer.create(getApplicationContext(), R.raw.success);

        new AlertDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("测试使用的appid不可用于商业用途，商用appid请务必联系我司商务进行分配")
                .setCancelable(false)
                .setPositiveButton("确定", (dialog, which) -> dialog.dismiss())
                .show();

        TextView markText = findViewById(R.id.tv_mark);
        List<String> labels = new ArrayList<>();
        labels.add("身份证识别");
        markText.setBackgroundDrawable(new WaterMarkBg(this, labels, -30, 15));
    }

    private static boolean hasNFC(Context context) {
        PackageManager packageManager = context.getPackageManager();
        return packageManager.hasSystemFeature(PackageManager.FEATURE_NFC);
    }

    /**
     * 统一配置读卡SDK参数信息
     * 测试使用的 appid 不可以用于商用(否则后果自负)。
     * 商用的 appid 请务必联系我司商务进行分配。
     */
    private void initBuilder() {

        readSettingBuilder = ReadCardManager.Companion
                .builder(getBaseContext())
                .buildOpenSound(true)
                .buildOpenLog(true, "")
                // 测试使用的 appid 不可以用于商用(否则后果自负)。
                // 商用的 appid 请务必联系我司商务进行分配。
                .buildAppId("test")
                .buildIpAndPort("", 0)
                .buildReadCardType(ReadCardType.NFC)
                .buildDecodeImageType(DecodeImageType.LOCAL_DECODE);

        readCardManager = readSettingBuilder.buildCreate();

        // 判断是否支持NFC
        if (hasNFC(getBaseContext())) {
            readTypeRadioGroup.getChildAt(1).setVisibility(View.VISIBLE);
        } else {
            readTypeRadioGroup.getChildAt(1).setVisibility(View.GONE);
            RadioButton radioButton = (RadioButton) readTypeRadioGroup.getChildAt(0);
            radioButton.setChecked(true);
//            bu_once_open.setVisibility(View.VISIBLE);
            llSerialPort.setVisibility(View.GONE);
            // 切换USB类型
            readSettingBuilder.buildReadCardType(ReadCardType.USB);
        }

        initDefData();
    }

    /**
     * 设置缓存值
     */
    private void initDefData() {
        String ip = SpUtlils.INSTANCE.getString("SOCKETIP", "");
        String port = SpUtlils.INSTANCE.getString("PORT", "");
        if (!TextUtils.isEmpty(ip) && !TextUtils.isEmpty(port)) {
            et_ip.setText(ip);
            et_port.setText(port);
            readSettingBuilder.buildIpAndPort(ip, Integer.parseInt(port));
        }
        String appid = SpUtlils.INSTANCE.getString("APPID", "");
        if (!TextUtils.isEmpty(appid)) {
            et_appid.setText(appid);
            readSettingBuilder.buildAppId(appid);
        }
        String serailPort = SpUtlils.INSTANCE.getString("serailPort", "");
        if (!TextUtils.isEmpty(serailPort)) {
            et_address.setText(serailPort);
        }

        int baudrate = SpUtlils.INSTANCE.getInt("baudrate", 115200);
        et_baudrate.setText(String.valueOf(baudrate));

        closeRead();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void initlistener() {
        tv_state.setMovementMethod(ScrollingMovementMethod.getInstance());

        DoubleClickUtil.signleClick(bu_init, v -> initSDK());

        DoubleClickUtil.signleClick(bu_open, v -> openRead());

        // 去除单次读卡
//        DoubleClickUtil.signleClick(bu_once_open, v -> {
//            onecOpenRead();
//        });

        DoubleClickUtil.signleClick(bu_close, v -> {
            if (lastStatus == 1022 || lastStatus == 1000 || lastStatus == 1024) {
                closeRead();
                Toast.makeText(getBaseContext(), "关闭成功，请重新初始化", Toast.LENGTH_SHORT).show();
            }
        });

        DoubleClickUtil.signleClick(bu_save, v -> {
            if (saveData()) {
                Toast.makeText(getBaseContext(), "保存成功，请初始化", Toast.LENGTH_SHORT).show();
            }
        });

        bu_openLog.setOnCheckedChangeListener((compoundButton, b) -> readSettingBuilder.buildOpenLog(b, ""));
        bu_sound.setOnCheckedChangeListener((compoundButton, b) -> readSettingBuilder.buildOpenSound(b));

        tv_state.setOnLongClickListener(v -> {
            tv_state.setText("清空日志");
            return true;
        });

        // 图片解码类型
        imageTypeRadioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.rb_no_image:
                    readSettingBuilder.buildDecodeImageType(DecodeImageType.NO_IMAGE);
                    break;
                case R.id.rb_server_image:
//                    readSettingBuilder.buildDecodeImageType(DecodeImageType.SERVER_DECODE);
                    break;
                case R.id.rb_local_image:
                    readSettingBuilder.buildDecodeImageType(DecodeImageType.LOCAL_DECODE);
                    break;
            }
        });

        // 读卡类型
        readTypeRadioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.rb_nfc:
                    bu_once_open.setVisibility(View.GONE);
                    llSerialPort.setVisibility(View.GONE);
                    // 切换NFC类型
                    readSettingBuilder.buildReadCardType(ReadCardType.NFC);
                    break;
                case R.id.rb_usb:
                    bu_once_open.setVisibility(View.GONE);
                    llSerialPort.setVisibility(View.GONE);
                    // 切换USB类型
                    readSettingBuilder.buildReadCardType(ReadCardType.USB);
                    break;
                case R.id.rb_serialPort:
                    bu_once_open.setVisibility(View.GONE);
                    llSerialPort.setVisibility(View.VISIBLE);
                    // 切换串口类型
                    readSettingBuilder.buildReadCardType(ReadCardType.SERIALPORT);
                    break;
            }
            // 类型切换了，重新初始化
            isInitOk = false;
            readCardManager.readCardStop();
        });
    }

    private void initSDK() {
        if (isInitOk) {
            tv_state.append("\n已经初始化过了");
            Toast.makeText(MainActivitys.this, "已经初始化过了", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!saveData()) {
            return;
        }
        switch (readCardManager.readCardType()) {
            case NFC:
            case USB:
                readCardManager.readCardInit(code -> {
                    if (code == StatusCode.ININ_OK.getCode()) {
                        isInitOk = true;
                        Log.e("mtj", "初始化成功");
                        runOnUiThread(() -> {
                            tv_state.setText("初始化成功");
                            bu_open.setEnabled(true);
                            bu_once_open.setEnabled(true);
                            handler.sendEmptyMessageDelayed(1, 800);
                        });
                    } else {
                        isInitOk = false;
                        Log.e("mtj", "初始化失败");
                        runOnUiThread(() -> {
                            tv_state.setText("初始化失败");
                        });
                    }
                });
                break;
            case SERIALPORT:
                String serailPort = et_address.getText().toString().trim();
                if (TextUtils.isEmpty(serailPort)) {
                    Toast.makeText(getBaseContext(), "请输入串口号", Toast.LENGTH_SHORT).show();
                    return;
                }
                String baudrate = et_baudrate.getText().toString().trim();
                if (TextUtils.isEmpty(baudrate)) {
                    Toast.makeText(getBaseContext(), "请输入波特率", Toast.LENGTH_SHORT).show();
                    return;
                }
                readCardManager.readCardInit(new File("/dev/" + serailPort), Integer.parseInt(baudrate), code -> {
                    if (code == StatusCode.ININ_OK.getCode()) {
                        isInitOk = true;
                        Log.e("mtj", "初始化成功");
                        runOnUiThread(() -> {
                            tv_state.setText("初始化成功");
                            bu_open.setEnabled(true);
                            handler.sendEmptyMessageDelayed(1, 800);
                        });
                    } else {
                        isInitOk = false;
                        Log.e("mtj", "初始化失败");
                        runOnUiThread(() -> {
                            tv_state.setText("初始化失败");
                        });
                    }
                });
                break;
        }
    }

    private boolean saveData() {
        tv_state.setText("");
        String appid = et_appid.getText().toString().trim();
        if (TextUtils.isEmpty(appid)) {
            Toast.makeText(this, "请输入appid", Toast.LENGTH_SHORT).show();
            return false;
        }
        String ip = et_ip.getText().toString().trim();
        String port = et_port.getText().toString().trim();
        if (TextUtils.isEmpty(ip) || TextUtils.isEmpty(port)) {
            Toast.makeText(this, "请输入IP和端口", Toast.LENGTH_SHORT).show();
            return false;
        }
        tv_state.append("\nappid-->");
        tv_state.append(appid);
        tv_state.append("\nip-->");
        tv_state.append(ip + ":" + port);
        SpUtlils.INSTANCE.putString("SOCKETIP", ip);
        SpUtlils.INSTANCE.putString("PORT", port);
        SpUtlils.INSTANCE.putString("APPID", appid);
        if (readCardManager.readCardType() == ReadCardType.SERIALPORT) {
            String serailPort = et_address.getText().toString().trim();
            if (TextUtils.isEmpty(serailPort)) {
                Toast.makeText(this, "请输入串口号", Toast.LENGTH_SHORT).show();
                return false;
            }
            tv_state.append("\n串口号-->");
            tv_state.append(serailPort);
            SpUtlils.INSTANCE.putString("serailPort", serailPort);
            String baudrate = et_baudrate.getText().toString().trim();
            if (TextUtils.isEmpty(baudrate)) {
                Toast.makeText(getBaseContext(), "请输入波特率", Toast.LENGTH_SHORT).show();
                return false;
            }
            tv_state.append("\n波特率-->");
            tv_state.append(baudrate);
            SpUtlils.INSTANCE.putInt("baudrate", Integer.parseInt(baudrate));

            LogUtils.INSTANCE.i("串口号-->" + serailPort + "  波特率-->" + baudrate);
        }
        // 更换AppId  Ip  Port
        readSettingBuilder
                .buildAppId(appid)
                .buildIpAndPort(ip, Integer.parseInt(port));
        // 重新初始化
        closeRead();
        return true;
    }

    private void openRead() {
        if (!isInitOk) {
            tv_state.append("\n未初始化成功");
            Toast.makeText(getBaseContext(), "请初始化SDK", Toast.LENGTH_SHORT).show();
            return;
        }
        if (isStartRead) {
            tv_state.append("\n读卡已开启");
            Toast.makeText(getBaseContext(), "读卡已开启", Toast.LENGTH_SHORT).show();
            return;
        }
        isStartRead = true;
        String deviceId = readCardManager.readCardDeviceid();
        txtDeviceDN.setText(deviceId);
        bu_open.setEnabled(false);
        bu_once_open.setEnabled(false);
        bu_save.setEnabled(false);
        bu_close.setEnabled(true);
        for (int i = 0; i < imageTypeRadioGroup.getChildCount(); i++) {
            imageTypeRadioGroup.getChildAt(i).setEnabled(false);
        }
        for (int i = 0; i < readTypeRadioGroup.getChildCount(); i++) {
            readTypeRadioGroup.getChildAt(i).setEnabled(false);
        }
        switch (readCardManager.readCardType()) {
            case USB:
            case SERIALPORT:
                readCardManager.readCardStart(MainActivitys.this);
                break;
        }
    }

    private void onecOpenRead() {
        if (!isInitOk) {
            tv_state.append("\n未初始化成功");
            return;
        }
        String deviceId = readCardManager.readCardDeviceid();
        txtDeviceDN.setText(deviceId);
        bu_open.setEnabled(false);
        bu_once_open.setEnabled(true);
        bu_close.setEnabled(true);
        readCardManager.readCardOnceStart(MainActivitys.this);
    }

    private void closeRead() {
        bu_close.setEnabled(false);
        bu_open.setEnabled(true);
        bu_once_open.setEnabled(true);
        bu_save.setEnabled(true);
        for (int i = 0; i < imageTypeRadioGroup.getChildCount(); i++) {
            imageTypeRadioGroup.getChildAt(i).setEnabled(true);
        }
        for (int i = 0; i < readTypeRadioGroup.getChildCount(); i++) {
            readTypeRadioGroup.getChildAt(i).setEnabled(true);
        }
        isInitOk = false;
        isStartRead = false;
        readCardManager.readCardStop();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d("readcard", "onStart");
        //此处adapter需要重新获取，否则无法获取message
        nfcUtils.mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        //一旦截获NFC消息，就会通过PendingIntent调用窗口
        nfcUtils.mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()), 0);
    }

    /**
     * 获得焦点，按钮可以点击
     */
    @Override
    public void onResume() {
        super.onResume();
        Log.d("readcard", "onResume");
        //设置处理优于所有其他NFC的处理
        if (nfcUtils.mNfcAdapter != null) {
            nfcUtils.mNfcAdapter.enableForegroundDispatch(this, nfcUtils.mPendingIntent, null, null);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d("readcard", "onPause");
        //恢复默认状态
        if (nfcUtils.mNfcAdapter != null) {
            nfcUtils.mNfcAdapter.disableForegroundDispatch(this);
        }
    }

    @SuppressLint("MissingSuperCall")
    @Override
    //在onNewIntent方法中进行NFC标签相关操作,执行intent传递过来的Tag数据
    public void onNewIntent(Intent intent) {
        //1.获取Tag对象
        super.onNewIntent(intent);
        if (!isStartRead) {
            tv_state.append("\n请先初始化和开始读卡");
            Toast.makeText(this, "请先初始化和开始读卡", Toast.LENGTH_SHORT).show();
            return;
        }
        if (readCardManager.readCardType() == ReadCardType.NFC) {
            readCardManager.readCardStart(intent, this);
        } else {
            tv_state.append("\n非NFC读卡类型");
            Toast.makeText(this, "非NFC读卡类型", Toast.LENGTH_SHORT).show();
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onReadCardState(int type, @NotNull String msg) {
        lastStatus = type;
        //读卡失败
        if (type == 1022) {
            readTime++;
            txtElapsedTime.setText("解码次数" + readTime + "  解码成功次数" + successTime + "  解码时间：" + "ms  \n" +
                    "成功率:" + keepTwoDecimalPlaces(successTime * 100F / readTime) + "%   平均耗时：" + keepTwoDecimalPlaces(alltime * 1F / successTime) + "ms   最小耗时：" + smallTime + "ms");
        }
        if (readTime % 100 == 0) {
            tv_state.setText("");
        }
        tv_state.append("\n");
        tv_state.append("status: " + type + "  ，msg:" + msg);
        handler.postDelayed(() -> {
            logNestedScrollView.fullScroll(View.FOCUS_DOWN);
        }, 200);
    }

    @Override
    public void onReadICCardSuccess(@NotNull String icnumber, int type) {
        clear();
        txtUid.setText(icnumber);
        if (bu_sound.isChecked()) {
            player.start();
        }
        tv_state.append("\n");
        tv_state.append("type: " + type + "\nicnumber:" + icnumber);
        handler.postDelayed(() -> {
            logNestedScrollView.fullScroll(View.FOCUS_DOWN);
        }, 200);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onReadIDCardSuccess(@NotNull IdCardData bean) {
        clear();
        if (readTime % 100 == 0) {
            tv_state.setText("");
        }
        tv_state.append("\n");
        tv_state.append("解码完成");
        if (bu_sound.isChecked()) {
            player.start();
        }
        successTime++;
        readTime++;
        alltime += bean.getDistime();
        if (bean.getDistime() < smallTime) {
            smallTime = bean.getDistime();
        }
        txtElapsedTime.setText("解码次数" + readTime + "  解码成功次数" + successTime + "  解码时间：" + bean.getDistime() + "ms  \n" +
                "成功率:" + keepTwoDecimalPlaces(successTime * 100F / readTime) + "%   平均耗时：" + keepTwoDecimalPlaces(alltime * 1F / successTime) + "ms   最小耗时：" + smallTime + "ms");
        if (null != bean.getBitmap()) {
            imgMan.setImageBitmap(bean.getBitmap());
        }
        txtName.setText(bean.getName());
        txtSex.setText(bean.getSex());
        txtNation.setText(bean.getNation());
        txtPolice.setText(bean.getIssue());
        txtCardID.setText(bean.getId());
        txtValid.setText(bean.getStartDate() + "-" + bean.getEndDate());
        try {
            txtY.setText(bean.getBirthday().substring(0, 4));
            txtM.setText(bean.getBirthday().substring(4, 6));
            txtD.setText(bean.getBirthday().substring(6, 8));
        } catch (Exception e) {
        }
        txtAddress.setText(bean.getAddress());
        txtDN.setText(bean.getDn());
        txtUid.setText(bean.getUuid());
        handler.postDelayed(() -> {
            logNestedScrollView.fullScroll(View.FOCUS_DOWN);
        }, 200);
    }

    private void clear() {
        txtName.setText("");
        txtSex.setText("");
        txtNation.setText("");
        txtPolice.setText("");
        txtCardID.setText("");
        txtValid.setText("");
        txtY.setText("");
        txtM.setText("");
        txtD.setText("");
        txtAddress.setText("");
        txtDN.setText("");
        txtUid.setText("");
        imgMan.setImageDrawable(getResources().getDrawable(R.mipmap.ic_launcher));
    }

    private String keepTwoDecimalPlaces(double value) {
        try {
            DecimalFormat df = new DecimalFormat("#0.00");
            return df.format(value);
        } catch (Exception e) {
        }
        return String.valueOf(value);
    }

    /* 判断程序是否有所需权限 android22以上需要自申请权限 */
    private boolean hasPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return checkSelfPermission(PERMISSION_READ_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                    checkSelfPermission(PERMISSION_WRITE_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                    checkSelfPermission(PERMISSION_INTERNET) == PackageManager.PERMISSION_GRANTED &&
                    checkSelfPermission(PERMISSION_ACCESS_NETWORK_STATE) == PackageManager.PERMISSION_GRANTED;
        } else {
            return true;
        }
    }

    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(Permission, PERMISSIONS_REQUEST);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSIONS_REQUEST) {
            boolean granted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED)
                    granted = false;
            }
            if (!granted) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
                    if (!shouldShowRequestPermissionRationale(PERMISSION_READ_STORAGE)
                            || !shouldShowRequestPermissionRationale(PERMISSION_WRITE_STORAGE)
                            || !shouldShowRequestPermissionRationale(PERMISSION_INTERNET)
                            || !shouldShowRequestPermissionRationale(PERMISSION_ACCESS_NETWORK_STATE)) {
                        Toast.makeText(getApplicationContext(), "需要开启文件存储权限", Toast.LENGTH_SHORT).show();
                    }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        player.release();
        readCardManager.readCardStop();
    }

}
      